# -*- coding: utf-8 -*-
from django.db import models
from django.db.models import permalink
from django.template import loader, Context
from datetime import datetime
from django.utils.translation import ugettext as _
from django.conf import settings

# Choices in various dropdowns. Labels read "Yes", "No" and "Unknown".
TRI_STATE = (('Y', 'Yes'), ('N', 'No'), ('U', 'Unknown'),)


class Topic(models.Model):
    """A topic, e.g. 'statistics'"""
    name = models.CharField(max_length=255)
    slug = models.SlugField(
            max_length=255,
            help_text="Automatically built from the name.",)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name= u"topic" #set to the topic word in your own language
        verbose_name_plural = u"topics"
        ordering = ('name',)



class Format(models.Model):
    """A format of data used in a dataset."""
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.SlugField(
            max_length=255,
            help_text="Created automatically from data in the name field.",)
    is_open = models.CharField(_("Is open standard"), default='U', max_length=1, choices=TRI_STATE)
    url = models.URLField(verify_exists=False, blank=True)

    def __unicode__(self):
        return self.name

    def open_label(self):
        """Returns the human readable label of a format's openness."""
        if self.is_open == "Y":
            return _("Open") #open
        elif self.is_open == "N":
            return _("Proprietary") #proprietary
        else:
            return _("Openness unknown") #openness unknown

    class Meta:
        verbose_name= u"format"
        verbose_name_plural = u"format"
        ordering = ('name',)


class License(models.Model):
    """The license under which a dataset is made available."""
    name = models.CharField(max_length=255)
    description = models.TextField()
    url = models.URLField(_("URL"), verify_exists=False, blank=True, help_text="License URL if available. Used in metadata.")
    is_free = models.BooleanField(_("Is free"), default=False)

    def is_free_text(self):
        if self.is_free:
            return _("Yes") #Yes
        else:
            return _( "No" ) #No

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name= u"license"
        verbose_name_plural = u"licenses"



class OrgType(models.Model):
    """A type of an organization, e.g. 'Government agency' or 'Municipaliy'"""
    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name= u"type"
        verbose_name_plural = u"types"
        ordering = ('name',)


class Organization(models.Model):
    """An organization that maintains a dataset (e.g. a government agency or
    city council."""
    name = models.CharField(max_length=255)
    url = models.URLField(verify_exists=False) #homepage of e.g. an agency
    orgtype = models.ForeignKey(OrgType)
    updated = models.DateTimeField(default=datetime.now)
    slug = models.SlugField(
        max_length=255,
        help_text="Automatically built from the name.",)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name= u"organisation"
        verbose_name_plural = u"organisations"
        ordering = ('name',)




class Dataset(models.Model):
    """A single dataset.""" 
    name = models.CharField(max_length=255)
    organization = models.ForeignKey(Organization, related_name='datasets')
    license = models.ForeignKey(License, related_name='datasets')
    description = models.TextField()
    updated = models.DateTimeField(auto_now=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    url = models.URLField(verify_exists=False)
    formats = models.ManyToManyField(Format, related_name='datasets')
    topics = models.ManyToManyField(Topic, related_name='datasets')

    def to_rdfxml(self):
        """Creates an RDF/XML representation of the dataset."""
        template=loader.get_template('catalog_item.rdf')
        context=Context({ 'dataset': self, 'site_base_url': settings.SITE_BASE_URL })
        return template.render(context)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name= u"dataset"
        verbose_name_plural = u"dataset"

    @models.permalink
    def get_absolute_url(self):
        return ('vwcatalogitem', None, { 'item_id': self.id})



class Suggestion(models.Model):
    """A suggestion for a dataset submitted by users. See forms.py for the form
    class."""
    name = models.CharField(max_length=255)
    agency = models.CharField(max_length=255)
    description = models.TextField()
    url = models.URLField(verify_exists=False)
    submitter_name = models.CharField(max_length=255)
    submitter_email = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name= u"suggestion" #set to Suggestion
        verbose_name_plural = u"suggestions" #set to suggestions

